package com.bestcem.xm.om.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.ObjectId;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bestcem.xm.common.core.domain.web.ServiceResult;
import com.bestcem.xm.om.constant.CommonConstant;
import com.bestcem.xm.om.constant.OmErrorMsg;
import com.bestcem.xm.om.dao.OmRoleDao;
import com.bestcem.xm.om.dao.OmUserDao;
import com.bestcem.xm.om.dao.OmUserIndustryDao;
import com.bestcem.xm.om.entity.OmIndustry;
import com.bestcem.xm.om.entity.OmRole;
import com.bestcem.xm.om.entity.OmUser;
import com.bestcem.xm.om.entity.OmUserIndustry;
import com.bestcem.xm.om.enums.OmRoleTypeEnum;
import com.bestcem.xm.om.enums.OmUserStatusEnum;
import com.bestcem.xm.om.grpc.service.converter.OmUserConverter;
import com.bestcem.xm.om.service.OmUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zq.ding <zq.ding@idiaoyan.com>
 * @version v1.0
 * @date 2021/12/27 14:53
 */
@Slf4j
@Service
public class OmUserServiceImpl implements OmUserService {
    public static final String SALE = "销售";
    public static final String SALE_LEADER = "销售Leader";

    @Resource
    private OmUserDao omUserDao;
    @Resource
    private OmRoleDao omRoleDao;
    @Resource
    private OmUserIndustryDao omUserIndustryDao;

    private static final String PHONE_ERROR_MSG = "手机号不合法";
    private static final String SALE_INDUSTRY_ERROR_MSG = "销售需要选择行业";
    private static final String USERNAME_DUPLICATE_MSG = "用户名重复";
    private static final String PHONE_DUPLICATE_MSG = "手机号重复";

    @Override
    public ServiceResult<String> getUserPermissions(String userId) {
        if (!ObjectId.isValid(userId)) {
            return ServiceResult.fail("用户id不合法");
        }
        OmUser omUser = omUserDao.findByIdAndStatus(userId, OmUserStatusEnum.ENABLE.getIndex());
        if (Objects.isNull(omUser)) {
            return ServiceResult.fail("查找用户失败");
        }
        OmRole omRole = omRoleDao.findById(omUser.getRoleId());
        if (Objects.isNull(omRole)) {
            return ServiceResult.fail("查找角色失败");
        }
        if (OmRoleTypeEnum.SUPER_ADMIN.getIndex().equals(omRole.getType()) && OmRoleTypeEnum.SUPER_ADMIN.getName().equals(omRole.getTitle())) {
            return ServiceResult.success(CommonConstant.ALL_PERIMISSION);
        }
        String permissions = omRole.getPermissions();
        // 过滤掉value为空
        if (StrUtil.isBlank(permissions)) {
            return ServiceResult.fail("查找权限失败");
        }
        JSONObject jsonObject = JSON.parseObject(permissions);
        return ServiceResult.success(jsonObject.toJSONString());
    }

    @Override
    public ServiceResult<com.bestcem.xm.om.grpc.v1.services.OmUser> getGrpcUserById(String userId) {
        if (!ObjectId.isValid(userId)) {
            return ServiceResult.fail("id不合法");
        }
        OmUser omUser = omUserDao.findById(userId);
        if (Objects.isNull(omUser)) {
            return ServiceResult.fail(OmErrorMsg.USER_NOT_FOUND);
        }
        com.bestcem.xm.om.grpc.v1.services.OmUser grpcUser = OmUserConverter.convertToGrpcUser(omUser);
        return ServiceResult.success(grpcUser);
    }

    @Override
    public ServiceResult<List<com.bestcem.xm.om.grpc.v1.services.OmUser>> listOmUsers
            (com.bestcem.xm.om.grpc.v1.services.OmUser grpcUser) {
        OmUser omUser = OmUserConverter.convertToOmUser(grpcUser);
        List<OmUser> omUsers = omUserDao.findByCondition(omUser);
        if (CollUtil.isEmpty(omUsers)) {
            return ServiceResult.fail("查询信息为空");
        }
        List<com.bestcem.xm.om.grpc.v1.services.OmUser> resultList = new ArrayList<>();
        omUsers.forEach(user -> resultList.add(OmUserConverter.convertToGrpcUser(user)));
        return ServiceResult.success(resultList);
    }

    /**
     * 组装成列表
     *
     * @param industryId
     * @param industryList
     * @return
     * @auther xuan.yang@idiaoyan.com
     * @date 2022/1/6 10:55
     */
    private List<OmUserIndustry> convertToIndustryList
    (List<String> industryId, List<OmIndustry> industryList, String userId) {
        if (CollUtil.isEmpty(industryId)) {
            return Collections.emptyList();
        }
        List<OmUserIndustry> resultList = new ArrayList<>();
        Map<String, String> industryMap = industryList.stream().collect(Collectors
                .toMap(OmIndustry::getId, OmIndustry::getName, (x, y) -> y));
        industryId.forEach(id -> {
            OmUserIndustry omUserIndustry = new OmUserIndustry();
            omUserIndustry.setIndustryId(id);
            omUserIndustry.setIndustryName(industryMap.get(id));
            omUserIndustry.setOmUserId(userId);
            omUserIndustry.setCreateTime(LocalDateTime.now());
            omUserIndustry.setUpdateTime(omUserIndustry.getCreateTime());
            if (StrUtil.isNotBlank(omUserIndustry.getIndustryName())) {
                resultList.add(omUserIndustry);
            }
        });
        return resultList;
    }

    private Set<String> getLeaderIndustryId(List<OmRole> allRoles) {
        List<String> saleLeaderRoleIds = allRoles.stream()
                .filter(role -> SALE_LEADER.equals(role.getTitle()))
                .map(OmRole::getId)
                .collect(Collectors.toList());
        if (CollUtil.isEmpty(saleLeaderRoleIds)) {
            return Collections.emptySet();
        }
        List<OmUser> omUsers = this.omUserDao.listByRoleId(saleLeaderRoleIds);
        if (CollUtil.isEmpty(omUsers)) {
            return Collections.emptySet();
        }
        List<String> omUserIds = omUsers.stream()
                .map(OmUser::getId)
                .collect(Collectors.toList());
        List<OmUserIndustry> omUserIndustrys = this.omUserIndustryDao.listByUserIds(omUserIds);
        return CollUtil.isEmpty(omUserIndustrys) ? Collections.emptySet() : omUserIndustrys.stream().map(OmUserIndustry::getIndustryId).collect(Collectors.toSet());
    }
}
